package milu.servlets;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.*;

import java.security.*;
import com.google.appengine.api.datastore.KeyFactory;
import javax.jdo.PersistenceManager;
import milu.models.*;
import milu.*;

import java.io.UnsupportedEncodingException; 
import java.security.MessageDigest; 
import java.security.NoSuchAlgorithmException; 

import java.util.regex.Pattern;

public class Register extends HttpServlet {
    private static final Pattern rfc2822 = Pattern.compile(
        "^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$"
        );


	public void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

        request.getRequestDispatcher("/register.jsp").forward(request, response);

    }
	public void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
        try {
            // do some validation
            String name = request.getParameter("name");
            String email = request.getParameter("email");
            String password = request.getParameter("password");

            if(name == null || name.equals("") || email == null || email.equals("") || password.equals("") || password == null) {
                request.setAttribute("error", "Completa tutto!");
                request.getRequestDispatcher("/register.jsp?returnurl="+request.getParameter("returnurl")).forward(request, response);
                return;
            }

            // before creating, check that this user with this email exists already
            if(MyUser.userExists(email)) {
                request.setAttribute("error", "Quest'email esiste!");
                request.getRequestDispatcher("/register.jsp?returnurl="+request.getParameter("returnurl")).forward(request, response);
                return;
            }
            // check if it's valid email
            if (!rfc2822.matcher(email).matches()) {
                request.setAttribute("error", "Controlla l'email!");
                request.getRequestDispatcher("/register.jsp?returnurl="+request.getParameter("returnurl")).forward(request, response);
                return;
            }

            MyUser newUser = new MyUser(name, email, SimpleSHA1.SHA1(password)); 
            PersistenceManager pm = Datastore.getPersistenceManager();
            try {
                pm.makePersistent(newUser);
            } finally {
                Datastore.finishRequest();
            }
            // login
            HttpSession session = request.getSession(true);
            session.setAttribute("userKey", newUser.getKey());

            response.sendRedirect(request.getParameter("returnurl"));
        } catch (NoSuchAlgorithmException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace();
        } 
    }
}
